package com.lanou3g.HW_0516.view;

import com.lanou3g.HW_0516.common.Constant;
import com.lanou3g.HW_0516.controller.Controller;
import com.lanou3g.HW_0516.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by dllo on 18/5/16.
 */
@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    private Controller controller = new Controller();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // TODO 获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = controller.login(username, password);

        String msg = "";
        // TODO 校验
        if (user != null) {
            // 登入成功
            msg = "登入成功";
            // 把用户信息存到session中去
            // 获取session对象

            // 把user 存入session之前,把对象中的密码置空
            user.setPwd("");
            HttpSession session = request.getSession();
            // 把用户信息存到session中,注意:晚上可以把User对象,直接存到session
            session.setAttribute(Constant.Session.USER, user);
            request.getRequestDispatcher("/WEB-INF/welcome.jsp").forward(request, response);
        } else {
            // 登入失败
            msg = "登入失败";
        }
        request.setAttribute("msg", msg);
        request.getRequestDispatcher("/user/msg.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request, response);
    }
}
